<script setup lang="ts">
import {
  voteWorksUpdateStatusApi,
  voteWorksAddApi,
  voteWorksUpdateApi,
} from "@/api/activity";

const route = useRoute(),
  internalInstance = getCurrentInstance();

const searchForm = ref<any>({
    actId: route.params.id,
  }),
  showWorksDialog = ref(false),
  submitLoading = ref(false),
  worksDialogTitle = ref(""),
  worksForm = ref<any>({
    worksList: [{ picture: [], video: [], status: 1 }],
  }),
  currentTabIndex = ref("0"),
  dialogImageUrl = ref(""),
  showViewer = ref(false);

const tableRef = ref(),
  worksRef = ref(),
  videoRef = ref<Array<any>>([]),
  pictureRef = ref<Array<any>>([]);

const filters = internalInstance?.appContext.config.globalProperties.$filters;

const actId = computed(() => {
  return route.params.id || "";
});

const search = async () => {
  tableRef.value.search();
};

// 修改作品状态
function changeStatus(): Promise<boolean> {
  let detail = this;
  let title = detail.status == 1 ? "禁用" : "启用";
  return new Promise(async (resolve, reject) => {
    const rs = await voteWorksUpdateStatusApi({
      status: detail.status == 1 ? 0 : 1,
      id: detail.id,
    });
    if (rs.code == 200) {
      resolve(true);
      ElNotification.success({
        message: `已${title}`,
      });
      search();
    } else resolve(false);
  });
}

// 新建
const handleCreate = () => {
  if (worksRef.value) worksRef.value.resetFields();
  worksForm.value = { worksList: [{ picture: [], video: [], status: 1 }] };
  worksDialogTitle.value = "新建作品";
  currentTabIndex.value = "0";
  showWorksDialog.value = true;
};

// 编辑
const handleEdit = (row: any) => {
  if (worksRef.value) worksRef.value.resetFields();
  worksForm.value = {
    worksList: [
      {
        ...row,
        video: row.videoStr ? row.videoStr.split(";") : [],
        picture: row.pictureStr ? row.pictureStr.split(";") : [],
      },
    ],
  };
  worksDialogTitle.value = `编辑作品【${row.title}】`;
  currentTabIndex.value = "0";
  showWorksDialog.value = true;
};

const tabPaneRemove = (name: number | string) => {
  worksForm.value.worksList.splice(Number(name), 1);
  currentTabIndex.value = "0";
};

const handleTabsAdd = () => {
  worksForm.value.worksList.push({ picture: [], video: [], status: 1 });
  currentTabIndex.value = (Number(currentTabIndex.value) + 1).toString();
};

// 删除视频
const deleteVideo = (index: number) => {
  ElMessageBox.confirm(`确认删除该视频吗？`, "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    videoRef.value[index].clearFiles();
    worksForm.value.worksList[index].video = [];
  });
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url!;
  showViewer.value = true;
};

// 删除图片
const handleRemove = (index: number, file: any) => {
  ElMessageBox.confirm(`确认删除该图片吗？`, "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let picture = worksForm.value.worksList[index].picture;
    let pIndex = picture.findIndex((item: any) => item === file.url);
    if (pIndex >= 0) {
      picture.splice(pIndex, 1);
    }
    if (worksForm.value.worksList[index].cover === file.url)
      worksForm.value.worksList[index].cover = "";
    pictureRef.value[index].handleRemove(file);
  });
};

// 设置封面
const setCover = (index: number, file: any) => {
  worksForm.value.worksList[index].cover = file.url;
};

const uploadPicture = (index: number, { name, url }: any) => {
  if (worksForm.value.worksList[index].picture.length == 1) {
    worksForm.value.worksList[index].cover = url;
  }
};

// 提交作品
const submitWorksForm = () => {
  worksRef.value.validate(async (valid: any, invalidFields: any) => {
    if (valid) {
      submitLoading.value = true;
      worksForm.value.worksList.forEach((item: any) => {
        item.pictureStr = item.picture.join(";");
        item.videoStr = item.video.join(";");
      });
      let rs = null;
      // 编辑
      if (worksForm.value.worksList[0].id !== undefined) {
        rs = await voteWorksUpdateApi(worksForm.value.worksList[0]);
      } else {
        rs = await voteWorksAddApi({
          ...worksForm.value,
          actId: actId.value,
        });
      }

      if (rs.code == 200) {
        ElMessage.success(`保存成功`);
        showWorksDialog.value = false;
        search();
      }
      submitLoading.value = false;
    } else {
      let key = Object.keys(invalidFields)[0];
      currentTabIndex.value = key.split(".")[1];
      worksRef.value.scrollToField(key);
    }
  });
};
</script>
<template>
  <main-content title="投票作品管理" back>
    <template #search-bar>
      <SearchBar inline :block="true">
        <template #normal>
          <el-form-item label="编号">
            <el-input
              v-model="searchForm.no"
              clearable
              placeholder="搜索作品编号"
            />
          </el-form-item>
          <el-form-item label="名称">
            <el-input
              v-model="searchForm.title"
              clearable
              placeholder="搜索作品名称"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="搜索作品状态"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
        </template>
        <template #toolbar>
          <el-form-item>
            <el-button v-has="['2018']" type="primary" @click="handleCreate"
              >新建作品</el-button
            >
          </el-form-item>
        </template>
      </SearchBar>
    </template>
    <LayoutTable
      ref="tableRef"
      url="activity/voteWorks/queryPage"
      :param="searchForm"
    >
      <el-table-column prop="no" align="center" label="编号" min-width="80" />
      <el-table-column
        prop="insName"
        align="center"
        label="封面图"
        min-width="80"
      >
        <template #default="scope">
          <el-image
            v-if="scope.row.cover"
            style="width: 50px; height: 50px"
            :src="scope.row.cover"
            fit="contain"
            :preview-src-list="[scope.row.cover]"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="title"
        align="center"
        label="名称"
        min-width="180"
        show-overflow-tooltip
      />
      <el-table-column
        prop="description"
        align="center"
        label="描述"
        min-width="80"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="上传时间" width="180">
        <template #default="scope">{{
          scope.row.createTime ? filters.dateFormat(scope.row.createTime) : ""
        }}</template>
      </el-table-column>
      <el-table-column
        prop="creatorName"
        align="center"
        label="上传人"
        min-width="180"
      />
      <el-table-column align="center" label="状态" min-width="180">
        <template #default="scope"
          ><ConfirmSwitch
            v-model="scope.row.status"
            active-text="启用"
            inactive-text="禁用"
            :title="`确认${scope.row.status == 0 ? '启用' : '禁用'}【${
              scope.row.name
            }】吗？`"
            :loading="scope.row.loading"
            :before-change="changeStatus.bind(scope.row)"
          ></ConfirmSwitch
        ></template>
      </el-table-column>
      <el-table-column
        v-has="['2018']"
        align="center"
        label="操作"
        min-width="80"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            type="primary"
            link
            size="small"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </LayoutTable>
  </main-content>
  <Dialog
    v-model="showWorksDialog"
    :title="worksDialogTitle"
    :loading="submitLoading"
    @confirm="submitWorksForm"
  >
    <el-form
      v-if="showWorksDialog"
      :model="worksForm"
      ref="worksRef"
      label-width="auto"
    >
      <div class="tabs-add" v-if="!worksForm.worksList[0].id">
        <el-button type="primary" icon="plus" @click="handleTabsAdd"
          >添加作品</el-button
        >
      </div>
      <el-tabs
        v-model="currentTabIndex"
        type="card"
        @tab-remove="tabPaneRemove"
      >
        <el-tab-pane
          v-for="(work, index) in worksForm.worksList"
          :name="index.toString()"
          :label="work.title || `作品${index + 1}`"
          :closable="worksForm.worksList.length > 1"
        >
          <el-form-item
            label="名称"
            :prop="`worksList.${index}.title`"
            :rules="[
              {
                required: true,
                message: '请输入作品名称',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              type="text"
              placeholder="请输入作品名称"
              clearable
              maxlength="30"
              :show-word-limit="true"
              v-model="work.title"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              type="textarea"
              placeholder="请输入作品描述"
              :autosize="{ minRows: 4, maxRows: 6 }"
              v-model="work.description"
              maxlength="250"
              show-word-limit
            >
            </el-input>
          </el-form-item>
          <el-form-item label="图片" prop="picture" class="picture">
            <Upload
              :ref="
                (el) => {
                  if (el) {
                    pictureRef[index] = el;
                  }
                }
              "
              v-model="work.picture"
              file-path="act-vote/"
              list-type="picture-card"
              :limit="5"
              @success="uploadPicture(index, $event)"
            >
              <el-icon>
                <Plus />
              </el-icon>
              <template #file="{ file }">
                <div>
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <el-icon><zoom-in /></el-icon>
                    </span>
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleRemove(index, file)"
                    >
                      <el-icon><Delete /></el-icon>
                    </span>
                  </span>
                  <div class="setcover-btn">
                    <el-button
                      v-if="work.cover != file.url"
                      type="primary"
                      link
                      size="small"
                      @click="setCover(index, file)"
                      >设为封面</el-button
                    >
                    <el-button v-else type="primary" link size="small"
                      >封面图</el-button
                    >
                  </div>
                </div>
              </template>
            </Upload>
          </el-form-item>
          <el-form-item label="视频" prop="video">
            <Upload
              :ref="
                (el) => {
                  if (el) {
                    videoRef[index] = el;
                  }
                }
              "
              v-model="work.video"
              file-path="act-vote/"
              accept=".mp4"
            >
              <el-button v-if="work.video.length == 0" type="primary"
                >点击上传</el-button
              >
              <el-button v-else type="primary" @click.stop="deleteVideo(index)"
                >删除</el-button
              >
              <template #file="{ file }">
                <div>
                  <video
                    :src="file.url"
                    controls
                    width="250"
                    height="150"
                  ></video>
                </div>
              </template>
            </Upload>
          </el-form-item>
          <el-form-item label="状态：">
            <el-switch
              v-model="work.status"
              inline-prompt
              active-text="启用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </Dialog>
  <el-image-viewer
    v-if="showViewer"
    :initial-index="0"
    :url-list="[dialogImageUrl]"
    @close="showViewer = false"
  >
  </el-image-viewer>
</template>
<style lang="scss" scoped>
:deep(.search) {
  .el-input__wrapper {
    width: 100%;
  }
}

.tabs-add {
  float: right;
  position: relative;
  z-index: 1;
}

.picture {
  :deep(.el-upload-list__item) {
    overflow: visible;
  }
}

.setcover-btn {
  padding: 0;
  position: absolute;
  bottom: -30px;
  left: 0;
  width: 100%;
  text-align: center;
}
</style>
